package com.eipv.multidatasource.service.impl;

import com.eipv.component.mybatis.base.entity.AbstractUser;
import com.eipv.component.mybatis.base.mapper.BaseMapper;
import com.eipv.component.mybatis.base.service.impl.BaseServiceImpl;
import com.eipv.component.snowflake.SnowflakeIdWorker;
import com.eipv.multidatasource.component.cache.PoolCache;
import com.eipv.multidatasource.component.cache.QueueCache;
import com.eipv.multidatasource.component.pool.LoadInThreadPool;
import com.eipv.multidatasource.component.task.ReadAndLoadInDbTask;
import com.eipv.multidatasource.entity.Table;
import com.eipv.multidatasource.mapper.mysql.MysqlTableMapper;
import com.eipv.multidatasource.service.LoadInService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.concurrent.atomic.AtomicLong;

@Service
public class LoadInServiceImpl extends BaseServiceImpl<Table, String> implements LoadInService {

    @Autowired
    private MysqlTableMapper mysqlTableMapper;


    @Override
    public void loadIn(AtomicLong total, long start) {
        PoolCache.loading();
        while (true) {
            try {
                File f = QueueCache.FILE_QUEUE.take();
                String tableName = f.getName().substring(0, f.getName().lastIndexOf("_"));

                LoadInThreadPool.getThreadPool().submit(new ReadAndLoadInDbTask(f, tableName, total, start));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }


    @Override
    public String nextId() {
        return SnowflakeIdWorker.nextStringId();
    }

    @Override
    public AbstractUser getCurrentUser() {
        return null;
    }

    @Override
    public BaseMapper<Table, String> getMapper() {
        return mysqlTableMapper;
    }


    @Override
    public void run() {
        AtomicLong total = new AtomicLong(0);
        long start = System.currentTimeMillis();
        this.loadIn(total, start);
    }
}
